package org.com.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.com.mapper.UserRolesMapper;
import org.com.pojo.UserRoles;
import org.com.pojo.Users;
import org.com.service.UserBalanceService;
import org.com.service.UsersService;
import org.com.mapper.UsersMapper;
import org.com.util.RedisUtil;
import org.com.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

/**
* @author 86134
* @description 针对表【users】的数据库操作Service实现
* @createDate 2025-02-26 22:01:09
*/
@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements UsersService{

    @Autowired
    private UsersMapper userMapper;
    @Autowired
    private UserRolesMapper userRolesMapper;
    @Autowired
    private RedisUtil redis;
    @Autowired
    private UserBalanceService userBalanceService;


    private static final String SMS_KEY_PRIFIX = "sms:code:phone:"; //定义验证码key前缀
    private static final String  UID_KEY= "uid:"; //定义验证码key前缀


    @Override
    public UserVO login(String username, String password) {
        System.out.println("尝试登录，用户名：" + username);
        Users user = userMapper.findByUsername(username);
        if (user != null) {
            System.out.println("找到用户：" + user.getUserName());
            System.out.println("数据库密码：" + user.getUserPassword());
            System.out.println("输入密码：" + password);
            // 检查用户状态
            if (user.getStatus() != null && user.getStatus() == 0) {
                System.out.println("用户账号已被禁用");
                return null;
            }
            if (user.getUserPassword().equals(password)) {
                // 获取用户所有角色信息
                QueryWrapper<UserRoles> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("user_id", user.getUserId())
                          .orderByDesc("created_at");
                List<UserRoles> userRoles = userRolesMapper.selectList(queryWrapper);
                
                UserVO userVO = new UserVO();
                userVO.setUserId(user.getUserId());
                userVO.setUsername(user.getUserName());
                userVO.setPhone(user.getPhoneNumber());
                userVO.setImageUrl(user.getImageUrl());
                userVO.setBio(user.getBio());
                userVO.setCallName(user.getCallName());  // 设置用户昵称
                userVO.setStatus(user.getStatus());  // 设置用户状态
                
                // 设置角色信息
                if (!userRoles.isEmpty()) {
                    System.out.println("找到用户角色数量：" + userRoles.size());
                    // 获取最新的角色记录
                    UserRoles latestRole = userRoles.get(0);
                    userVO.setRoleId(latestRole.getRoleId());
                    userVO.setApplyType(latestRole.getApplyType());
                    // 设置所有角色记录
                    userVO.setUserRoles(userRoles);
                    
                    // 判断按钮状态
                    boolean hasRole2ApplyType1 = false; // 是否有 roleId=2, applyType=1 的记录
                    boolean hasRole3ApplyType0 = false; // 是否有 roleId=3, applyType=0 的记录
                    boolean hasRole3ApplyType1 = false; // 是否有 roleId=3, applyType=1 的记录
                    boolean hasRole1ApplyType1 = false; // 是否有 roleId=1, applyType=1 的记录
                    
                    for (UserRoles role : userRoles) {
                        if (role.getRoleId() == 2 && role.getApplyType() == 1) {
                            hasRole2ApplyType1 = true;
                        } else if (role.getRoleId() == 3 && role.getApplyType() == 0) {
                            hasRole3ApplyType0 = true;
                        } else if (role.getRoleId() == 3 && role.getApplyType() == 1) {
                            hasRole3ApplyType1 = true;
                        } else if (role.getRoleId() == 1 && role.getApplyType() == 1) {
                            hasRole1ApplyType1 = true;
                        }
                    }
                    
                    // 根据条件设置按钮状态
                    if (hasRole1ApplyType1) {
                        userVO.setButtonStatus("APPLY_USER");
                    } else if (hasRole2ApplyType1 && hasRole3ApplyType0) {
                        userVO.setButtonStatus("UNDER_REVIEW");
                    } else if (hasRole3ApplyType1) {
                        userVO.setButtonStatus("EXPERT");
                    } else if (hasRole2ApplyType1) {
                        userVO.setButtonStatus("APPLY_EXPERT");
                    }
                    
                    System.out.println("按钮状态：" + userVO.getButtonStatus());
                } else {
                    System.out.println("未找到用户角色");
                }
                
                return userVO;
            } else {
                System.out.println("密码不匹配");
            }
        } else {
            System.out.println("未找到用户");
        }
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addUser(Users user, String code) {
        System.out.println("开始注册流程，用户信息：" + user);
        System.out.println("验证码：" + code);
        
        try {
            // 检查手机号是否已经存在
            QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("phone_number", user.getPhoneNumber());
            Users existingUserByPhone = userMapper.selectOne(queryWrapper);
            System.out.println("检查手机号是否存在：" + (existingUserByPhone != null ? "已存在" : "不存在"));
            
            if (existingUserByPhone != null) {
                System.out.println("手机号已被注册");
                return false;
            }
            
            String codeInRedis = (String) redis.get(SMS_KEY_PRIFIX + user.getPhoneNumber());
            System.out.println("Redis中的验证码：" + codeInRedis);
            
            if (codeInRedis == null) {
                System.out.println("验证码已过期或不存在");
                return false;
            }

            if (!codeInRedis.equals(code)) {//验证码是否正确
                System.out.println("验证码错误，输入：" + code + "，Redis中：" + codeInRedis);
                return false;
            }
            
            // 检查用户名是否已经存在
            queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_name", user.getUserName());
            Users existingUserByUsername = userMapper.selectOne(queryWrapper);
            System.out.println("检查用户名是否存在：" + (existingUserByUsername != null ? "已存在" : "不存在"));

            if (existingUserByUsername != null) {
                System.out.println("用户名已被注册");
                return false;
            }
            
            System.out.println("开始删除Redis中的验证码");
            redis.del(SMS_KEY_PRIFIX + user.getPhoneNumber());//成功后删除验证码
            
            System.out.println("开始插入新用户");
            // 插入新用户
            int result = userMapper.insert(user);
            if (result <= 0) {
                throw new RuntimeException("插入用户数据失败");
            }
            System.out.println("用户插入结果：成功");

            // 获取自动生成的user_id
            Integer userId = user.getUserId();
            if (userId == null) {
                throw new RuntimeException("获取用户ID失败");
            }
            System.out.println("新用户的user_id：" + userId);

            // 创建新的UserRole对象
            UserRoles userRole = new UserRoles();
            userRole.setUserId(userId);
            userRole.setApplyType(1);
            userRole.setRoleId(2); // 设置角色ID为2
            System.out.println("准备插入用户角色信息：" + userRole);

            // 插入新的UserRole对象到user_role表中
            int roleResult = userRolesMapper.insert(userRole);
            if (roleResult <= 0) {
                throw new RuntimeException("插入用户角色数据失败");
            }
            System.out.println("用户角色插入结果：成功");

            // 初始化用户余额
            boolean balanceResult = userBalanceService.initUserBalance(userId);
            if (!balanceResult) {
                throw new RuntimeException("初始化用户余额失败");
            }
            System.out.println("初始化用户余额结果：成功");

            return true;
        } catch (Exception e) {
            System.out.println("注册过程发生异常：" + e.getMessage());
            e.printStackTrace();
            throw new RuntimeException("注册失败：" + e.getMessage());
        }
    }
    @Override
    public boolean findPassword(String phone, String username, String newPassword) {
        // 验证验证码
        String codeInRedis = (String) redis.get(SMS_KEY_PRIFIX + phone);
        if (codeInRedis == null) {
            System.out.println("验证码已过期");
            return false;
        }

        // 查询用户表，验证手机号和用户名
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone_number", phone)
                   .eq("user_name", username);
        Users user = this.getOne(queryWrapper);
        if (user != null) {
            // 更新用户的密码
            user.setUserPassword(newPassword);
            this.updateById(user);
            // 删除验证码
            redis.del(SMS_KEY_PRIFIX + phone);
            System.out.println("密码修改成功");
            return true;
        } else {
            System.out.println("手机号或用户名错误");
            return false;
        }
    }

//    管理员授权请求
public boolean adminUpdateApplyType(Integer userId, Integer applyType) {
    if (applyType == 1) {  // 通过申请
        // 1. 删除原有的普通用户角色记录
        userRolesMapper.delete(new QueryWrapper<UserRoles>()
                .eq("user_id", userId)
                .eq("role_id", 2)
                .eq("apply_type", 1));
        
        // 2. 更新专家申请记录的状态
        QueryWrapper<UserRoles> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId)
                   .eq("role_id", 3)
                   .eq("apply_type", 0);
        
        UserRoles userRoles = new UserRoles();
        userRoles.setApplyType(1);
        
        return userRolesMapper.update(userRoles, queryWrapper) > 0;
    } else {  // 拒绝申请
        // 直接删除专家申请记录
        return userRolesMapper.delete(new QueryWrapper<UserRoles>()
                .eq("user_id", userId)
                .eq("role_id", 3)
                .eq("apply_type", 0)) > 0;
    }
}

    @Override
    public boolean userUpdateApplyType(Integer userId, Integer roleId, Integer applyType) {
        UserRoles userRole = new UserRoles();
        userRole.setUserId(userId);
        userRole.setRoleId(roleId);
        userRole.setApplyType(applyType);
        int result = userRolesMapper.insert(userRole);
        System.out.println("用户修改申请状态成功");
        return result > 0;
    }
    public List<Map<String, Object>> getApplyTypeUser() {
        return userMapper.getApplyTypeUser();
    }

    @Override
    public Users getUserProfile(Integer userId) {
        return userMapper.selectById(userId);
    }

    @Override
    public boolean updateUserProfile(Users user) {
        return userMapper.updateById(user) > 0;
    }

    @Override
    public List<Integer> getExpertUserIds() {
        return userMapper.getExpertUserIds();
    }

    @Override
    public Page<Users> getUserListWithRoles(Page<Users> page) {
        // 先获取用户基本信息的分页数据
        Page<Users> userPage = this.page(page);
        
        // 为每个用户添加角色信息
        for (Users user : userPage.getRecords()) {
            // 查询用户的角色信息
            QueryWrapper<UserRoles> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", user.getUserId())
                      .orderByDesc("created_at");
            List<UserRoles> userRoles = userRolesMapper.selectList(queryWrapper);
            
            // 将角色信息添加到用户对象中
            user.setUserRoles(userRoles);
        }
        
        return userPage;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean resetUserPassword(Integer userId) {
        try {
            // 查询用户是否存在
            Users user = userMapper.selectById(userId);
            if (user == null) {
                return false;
            }

            // 设置默认密码为123456
            user.setUserPassword("123456");
            
            // 更新用户密码
            return userMapper.updateById(user) > 0;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("重置密码失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteUserWithRoles(Integer userId) {
        try {
            // 1. 删除用户角色关联
            userRolesMapper.delete(new QueryWrapper<UserRoles>()
                    .eq("user_id", userId));

            // 2. 删除用户
            return userMapper.deleteById(userId) > 0;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("删除用户失败：" + e.getMessage());
        }
    }

    @Override
    public boolean updateUserStatus(Integer userId, Integer status) {
        try {
            Users user = userMapper.selectById(userId);
            if (user == null) {
                return false;
            }
            
            user.setStatus(status);
            return userMapper.updateById(user) > 0;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("更新用户状态失败：" + e.getMessage());
        }
    }

}




